<template>
  <div class="setting">
    <el-form ref="formRef" :model="form" class="myForm" label-position="left" label-width="auto">
      <div v-for="(item, index) in form.settingList" :key="index">
        <div class="drawer-title-item">
          <p></p>
          <span>{{ item.name }}</span>
        </div>
        <el-form-item label="定制文件：">
          <div class="file-tag">
            <template v-for="tag in item.customizationList" :key="tag.id">
              <el-tooltip effect="light" :content="tag.fileName" placement="top">
                <el-tag type="success">{{ tag.fileName }}</el-tag>
              </el-tooltip>
            </template>
          </div>
        </el-form-item>
        <el-form-item
          label="打印模式："
          :prop="`settingList.${index}.model`"
          :rules="[
            {
              required: true,
              message: '请选择打印模式',
              trigger: 'change'
            }
          ]"
        >
          <el-radio-group v-model="form.settingList[index].model" @change="onModelChange">
            <el-radio label="A4" value="A4"></el-radio>
            <el-radio label="A3" value="A3"></el-radio>
            <el-radio label="B5" value="B5"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="快捷定制："
          :prop="`settingList.${index}.optionId`"
          :rules="[
            {
              required: true,
              message: '请选择快捷定制',
              trigger: 'change'
            }
          ]"
        >
          <el-select
            v-model="form.settingList[index].optionId"
            placeholder="请选择快捷定制"
            clearable
            fit-input-width
          >
            <el-option
              v-for="item in form.settingList[index].optionTypeList"
              :key="item.id"
              :label="`${form.settingList[index].model} ${item.color} ${item.type}`"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="缩印（多页合一）："
          :prop="`settingList.${index}.reduced`"
          :rules="[
            {
              required: true,
              message: '请选择缩印方式',
              trigger: 'change'
            }
          ]"
        >
          <el-select
            v-model="form.settingList[index].reduced"
            placeholder="请选择缩印方式"
            clearable
            fit-input-width
          >
            <el-option
              v-for="item in reducedList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="装订方式："
          :prop="`settingList.${index}.bindingType`"
          :rules="[
            {
              required: true,
              message: '请选择装订方式',
              trigger: 'change'
            }
          ]"
        >
          <el-select
            v-model="form.settingList[index].bindingType"
            placeholder="请选择装订方式"
            clearable
            fit-input-width
          >
            <el-option
              v-for="item in bindingList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="皮纹纸颜色：">
          <el-select
            v-model="form.settingList[index].pageColor"
            placeholder="请选择皮纹纸颜色"
            clearable
            fit-input-width
            :disabled="form.settingList[index].bindingType === '不装订'"
          >
            <el-option
              v-for="item in userStore.pageColorList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="份数：">
          <el-input-number v-model="form.settingList[index].num" :min="1" />
        </el-form-item>

        <el-form-item label="折扣：">
          <el-input-number
            v-model="form.settingList[index].discount"
            :precision="1"
            :step="0.1"
            :min="0"
            :max="1"
          />
        </el-form-item>
      </div>
      <el-form-item label="备注信息：" v-if="form.settingList.length > 0">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="4"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label=" " v-if="form.settingList.length > 0">
        <el-button type="primary" @click="onSubmit">账单输出</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { useUserStore } from '@renderer/stores/user'
import { bindingList, reducedList } from '@renderer/views/option.js'

const emit = defineEmits(['submit'])
const userStore = useUserStore()
const formRef = ref(null)
const props = defineProps({
  settingList: {
    type: Array,
    default: () => []
  }
})
const form = reactive({
  settingList: []
})

watch(
  () => props.settingList,
  (newValue) => {
    // 使用深拷贝确保数据独立性

    if (form.settingList.length == 0) {
      let list = []
      newValue.forEach((element) => {
        let optionTypeList = userStore.optionInfo['A4']

        list.push({
          model: 'A4',
          option: {},
          num: 1,
          reduced: 1,
          discount: 1,
          bindingType: '',
          pageColor: '',
          optionTypeList,
          ...element
        })
      })
      form.settingList = JSON.parse(JSON.stringify(list))
    } else {
      let list1 = newValue.slice(form.settingList.length)
      let list = []
      list1.forEach((element) => {
        let optionTypeList = userStore.optionInfo['A4']
        list.push({
          model: 'A4',
          option: {},
          num: 1,
          reduced: 1,
          discount: 1,
          bindingType: '',
          pageColor: '',
          optionTypeList,
          ...element
        })
      })

      form.settingList = [...form.settingList, ...list]
    }
    console.log('settingList updated: ', form.settingList)
  },
  { deep: true, immediate: true } // 立即执行一次，处理初始值
)
const onModelChange = (val) => {
  console.log('打印模式:', val)
  form.option = {}
}
const onSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      let totalPrice = 0
      form.settingList.forEach((el) => {
        const option = el.optionTypeList.find((item) => item.id === el.optionId)
        if (option) {
          el.option = option
        }

        let pageNum = 0
        let fileNames = ''
        el.customizationList.forEach((element) => {
          pageNum += Math.ceil(element.filePageNum / el.reduced)
          fileNames = `${fileNames}[${element.id}]${element.fileName};`
          console.log(pageNum)
        })

        let bindInfo = bindingList.find((item) => item.label == el.bindingType)
        console.log(parseFloat(option.price), pageNum, bindInfo.price)

        // 双面页数要除以2，需要考虑奇数问题
        if (option.type == '双面') {
          pageNum = Math.ceil(pageNum / 2)
        }
        let price =
          (parseFloat(option.price) * pageNum + bindInfo.price * el.customizationList.length) *
          el.num *
          el.discount
        totalPrice += price
        el.content = `${el.name}：\n文件个数：${el.customizationList.length};\n页数${pageNum};\n${el.model}${el.option.color}${el.option.type}+${el.bindingType}*${el.num * el.customizationList.length}份......${price.toFixed(2)}元。\n\n`
      })
      form.totalPrice = totalPrice.toFixed(2)
      emit('submit', form)
    }
  })
}
</script>

<style lang="scss" scoped>
.file-tag {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  width: 100%;
  overflow: hidden;
}
</style>
<style>
.file-tag .el-tag {
  white-space: nowrap; /* 防止文本换行 */
  text-overflow: ellipsis; /* 显示省略号 */
  overflow: hidden; /* 确保文本超出部分被隐藏 */
}

.file-tag .el-tag .el-tag__content {
  white-space: nowrap; /* 防止文本换行 */
  text-overflow: ellipsis; /* 显示省略号 */
  overflow: hidden;
  width: 100%;
}
</style>
